﻿$(document).ready(function() {

    if ($("#IsGeneric").is(':checked') == true) {
        $("#EmailRow").hide();
    }

    $(".datepicker").datetimepicker({ dateFormat: 'dd/mm/yy', ampm: true });

    $('#Add').live("click", function() {
        var vals = new Array();
        $('#NotInUsersGroupSelected :selected').each(function(i, selected) {
            $.ajax({
                url: "/Account/AddPollAdministratorToGroup",
                data: ({ username1: vals[i] = $(selected).val(), username2: $('#UserName').val() }),
                cache: false,
                success: function(html) {
                    $('#rightColumn').html(html);
                }
            });
        });
    });


    $('#ResetPassword').live('click', function() {
        $("#resetpasswordspinnermsg").text("");
        $("#resetpasswordspinnermsg").hide();
        $("#resetpasswordspinner").show();
        $("#resetpasswordspinnermsg").text("  Sending...");
        $("#resetpasswordspinnermsg").show();
        $.ajax({
            type: 'POST',
            url: "/Account/ResetPasswordByUsername",
            data: ({ username: $("#UserName").val() }),
            cache: false,
            success: function(response) {
                if (response == "True") {
                    $("#resetpasswordspinner").hide();
                    $("#resetpasswordspinnermsg").text("  Password reset");
                }
                else {
                    $("#resetpasswordspinner").hide();
                    $("#resetpasswordspinnermsg").text("  Error");
                }
            }
        });
    });


    $("#submit").live('click', function() {
        if ($('#IsNew').val() == "False" && $("#IsEditable").val() == "False" && $("#SelectedRole").val() == "Poll Administrator") {
            $('#spinnermsg').text("Saving...");
            $("#spinnermsg").show();
            $("#spinner").show();
            $.ajax({
                type: 'POST',
                url: "/Account/AccountManager",
                data: $("#accountManagerForm").serialize(),
                cache: false,
                success: function(html) {
                    $('#accountManagerContainer').html(html);
                    if ($("#validationsummary").text() == "") {
                        $("#spinnermsg").text("Saved");
                        $("#spinnermsg").show();
                        $(".datepicker").datetimepicker({ dateFormat: 'dd/mm/yy', ampm: true });
                    }
                    else {
                        $("#validationsummary").show();
                    }
                }
            });
        }
        if ($('#IsNew').val() == "True" && $("#IsGeneric").is(':checked') == true) {
            var x = 0;
            $('.GenericEmail').each(function() {
                if (!isValidEmailAddress($(this).val())) {
                    $(this).addClass("input-validation-error");
                    $(this).parent().next().next().children(":first").text("Email format invalid.");
                    x++;
                } else {
                    $(this).removeClass("input-validation-error");
                    $(this).parent().next().next().children(":first").text("");
                }
            });
            if (x == 0) {
                if ($('#IsEditable').val() == "True") {
                    $("#UserName").removeClass("input-validation-error");
                    $("#UserNameMessage").text("");
                    $("#spinner").show();
                    $('#spinnermsg').text("Checking UserName...");
                    $("#spinnermsg").show();
                    if ($('#UserName').val() == "") {
                        $("#UserName").addClass("input-validation-error");
                        $('#spinnermsg').text("");
                        $("#spinnermsg").hide();
                        $("#spinner").hide();
                        $('#UserNameMessage').text("The UserName field is required.");
                        validusername = false;
                        return;
                    }
                    else {
                        $.ajax({
                            url: "/Account/UserNameIsValid",
                            data: ({ username: $('#UserName').val() }),
                            cache: false,
                            success: function(response) {
                                if (response == "False") {
                                    $("#UserName").addClass("input-validation-error");
                                    $('#spinnermsg').text("");
                                    $("#spinnermsg").hide();
                                    $("#spinner").hide();
                                    $('#UserNameMessage').text("The UserName is already in use.");
                                    validusername = false;
                                    return;
                                }
                                else {
                                    $('#spinnermsg').text("");
                                    $("#spinner").hide();
                                    $("#spinnermsg").hide();
                                    $('#UserNameMessage').text("The UserName is valid.");
                                    validusername = true;
                                    $('#spinnermsg').text("Saving...");
                                    $("#spinnermsg").show();
                                    $("#spinner").show();
                                    $.ajax({
                                        type: 'POST',
                                        url: "/Account/AccountManager",
                                        data: $("#accountManagerForm").serialize(),
                                        cache: false,
                                        success: function(html) {
                                            $('#accountManagerContainer').html(html);
                                            if ($("#validationsummary").text() == "") {
                                                $("#spinnermsg").text("Saved");
                                                $("#spinnermsg").show();
                                            }
                                            else {
                                                $("#validationsummary").show();
                                            }
                                        }
                                    });
                                    return;
                                }

                            }
                        });
                    }
                }
            }
            validemails = false;
        }
        if ($('#IsNew').val() == "True" && $("#IsGeneric").is(':checked') == false) {
            if ($('#IsNew').val() == "True") {
                $("#Email").removeClass("input-validation-error");
                $("#EmailMessage").text("");
                $('#spinnermsg').text("Checking Email...");
                $("#spinnermsg").show();
                $("#spinner").show();
                $.ajax({
                    url: "/Account/EmailIsValid",
                    data: ({ email: $('#Email').val() }),
                    cache: false,
                    success: function(response) {
                        if (response == "user") {
                            $.ajax({
                                url: "/Account/GetUserDetails",
                                data: ({ email: $('#Email').val(), selectedrole: $('#SelectedRole').val() }),
                                cache: false,
                                success: function(html) {
                                    $('#accountManagerContainer').html(html);
                                    $("#Email").removeClass("input-validation-error");
                                    $("#spinner").hide();
                                    $('#spinnermsg').text("");
                                    $("#spinnermsg").hide();
                                    $('#EmailMessage').text("Email is already in use.");
                                    validusername = true;
                                    $('#spinnermsg').text("Saving...");
                                    $("#spinnermsg").show();
                                    $("#spinner").show();
                                    $.ajax({
                                        type: 'POST',
                                        url: "/Account/AccountManager",
                                        data: $("#accountManagerForm").serialize(),
                                        cache: false,
                                        success: function(html) {
                                            $('#accountManagerContainer').html(html);
                                            if ($("#validationsummary").text() == "") {
                                                $("#spinnermsg").text("Saved");
                                                $("#spinnermsg").show();
                                                if (vars["pollName"] != undefined) $('#participant').append("<a href=\"../Participant/AddWeb?pollID=" + vars["pollID"] + "&pollName=" + vars["pollName"] + "&email=" + vars["email"] + "\">" + "Add this user as a participant in " + vars["pollName"] + "<a>");
                                            }
                                            else {
                                                $("#validationsummary").show();
                                            }
                                        }
                                    });
                                    validemail = true;
                                    return;
                                }
                            });
                            return;
                        }
                        else if (response == "invalid") {
                            $("#Email").removeClass("input-validation-error");
                            $("#spinner").hide();
                            $('#spinnermsg').text("");
                            $("#spinnermsg").hide();
                            $('#EmailMessage').text("Email is invalid.");
                            validemail = false;
                            return;
                        }
                        else {
                            if ($('#IsEditable').val() == "False") {
                                $.ajax({
                                    url: "/Account/GetNewUserDetails",
                                    data: ({ username: $('#UserName').val(), email: $('#Email').val(), firstname: $('#FirstName').val(),
                                        lastname: $('#LastName').val(), organisation: $('#Organisation').val(), position: $('#Position').val(),
                                        city: $('#City').val(), country: $('#Country').val(), selectedrole: $('#SelectedRole').val(), gender: $("input[@name=Gender]:checked").val(),
                                        isgeneric: $("#IsGeneric").is(':checked')
                                    }),
                                    cache: false,
                                    success: function(html) {
                                        $('#accountManagerContainer').html(html);
                                    }
                                });
                            }
                            if ($('#Email').val() == "") {
                                $("#Email").addClass("input-validation-error");
                                $("#spinner").hide();
                                $('#spinnermsg').text("");
                                $("#spinnermsg").hide();
                                $('#EmailMessage').text("The Email field is required.");
                                validemail = false;
                                return;
                            }
                            else if (!isValidEmailAddress($('#Email').val())) {
                                $("#Email").addClass("input-validation-error");
                                $("#spinner").hide();
                                $('#spinnermsg').text("");
                                $("#spinnermsg").hide();
                                $('#EmailMessage').text("The Email format is invalid.");
                                validemail = false;
                                return;
                            }
                            else {
                                $("#Email").removeClass("input-validation-error");
                                $("#spinner").hide();
                                $('#spinnermsg').text("");
                                $("#spinnermsg").hide();
                                $('#EmailMessage').text("The Email is valid.");
                                if ($('#IsEditable').val() == "True") {
                                    $("#UserName").removeClass("input-validation-error");
                                    $("#UserNameMessage").text("");
                                    $("#spinner").show();
                                    $('#spinnermsg').text("Checking UserName...");
                                    $("#spinnermsg").show();
                                    if ($('#UserName').val() == "") {
                                        $("#UserName").addClass("input-validation-error");
                                        $('#spinnermsg').text("");
                                        $("#spinnermsg").hide();
                                        $("#spinner").hide();
                                        $('#UserNameMessage').text("The UserName field is required.");
                                        validusername = false;
                                        return;
                                    }
                                    else {
                                        $.ajax({
                                            url: "/Account/UserNameIsValid",
                                            data: ({ username: $('#UserName').val() }),
                                            cache: false,
                                            success: function(response) {
                                                if (response == "False") {
                                                    $("#UserName").addClass("input-validation-error");
                                                    $('#spinnermsg').text("");
                                                    $("#spinnermsg").hide();
                                                    $("#spinner").hide();
                                                    $('#UserNameMessage').text("The UserName is already in use.");
                                                    validusername = false;
                                                    return;
                                                }
                                                else {
                                                    $('#spinnermsg').text("");
                                                    $("#spinner").hide();
                                                    $("#spinnermsg").hide();
                                                    $('#UserNameMessage').text("The UserName is valid.");
                                                    validusername = true;
                                                    $('#spinnermsg').text("Saving...");
                                                    $("#spinnermsg").show();
                                                    $("#spinner").show();
                                                    $.ajax({
                                                        type: 'POST',
                                                        url: "/Account/AccountManager",
                                                        data: $("#accountManagerForm").serialize(),
                                                        cache: false,
                                                        success: function(html) {
                                                            $('#accountManagerContainer').html(html);
                                                            if ($("#validationsummary").text() == "") {
                                                                $("#spinnermsg").text("Saved");
                                                                $("#spinnermsg").show();
                                                                if (vars["pollName"] != undefined) $('#participant').append("<a href=\"../Participant/AddWeb?pollID=" + vars["pollID"] + "&pollName=" + vars["pollName"] + "&email=" + vars["email"] + "\">" + "Add this user as a participant in " + vars["pollName"] + "<a>");
                                                            }
                                                            else {
                                                                $("#validationsummary").show();
                                                            }
                                                        }
                                                    });
                                                    return;
                                                }

                                            }
                                        });
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
        return false;
    });

    $('#Email').live("blur", function() {
        validateEmail();
    });

    $('#UserName').live("blur", function() {
        validateUserName();
    });

    var i = 1;
    $("#IsGeneric").live('click', function() {
        if ($("#IsGeneric").is(':checked')) {
            i = 1;
            $("#AddEmail").click();
            $("#EmailRow").hide();
            $("#AddEmail").show();
            $("#BulkTool").show();
        } else {
            $("#AddEmail").hide();
            $("#EmailRow").show();
            $("#BulkTool").hide();
            $(".editorRow").remove();
        }
    });

    $("#AddEmail").live('click', function() {
        $.ajax({
            url: "/Account/BlankEditorRow",
            cache: false,
            success: function(html) {
                $('#CreateTable > tbody > tr').eq(i).after(html);
                i++;
            }
        });
        return false;
    });


    $('#Remove').live("click", function() {
        $(this).parents("tr.editorRow:first").remove();
    });

    $("#al_bulk_delim").live('click', function() {
        var array = new Array();
        var emailRegex = /[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/igm;
        $.each($("#ta_bulk").val().match(emailRegex), function(index, value) {
            array[index] = value;
        });
        for (j = 0; j < array.length; j++) {
            $.ajax({
                url: "/Account/FilledEditorRow",
                data: ({ email: array[j] }),
                cache: false,
                success: function(html) {
                    var found = false;
                    $('.GenericEmail').each(function() {
                        if ($(this).val() == "" && found == false) {
                            $(this).parent().parent().after(html);
                            $(this).parent().parent().remove();
                            found = true;
                        }
                    });
                    if (!found) {
                        $('#CreateTable > tbody > tr').eq(i).after(html);
                        i++;
                    }
                }
            });
        }
        return false;
    });
    var success = function(file, server_data, receivedResponse) {
        var array = jQuery.parseJSON(server_data);
        for (z = 0; z < array.length; z++) {
            $.ajax({
                url: "/Account/FilledEditorRow",
                data: ({ email: array[z] }),
                cache: false,
                success: function(html) {
                    var found = false;
                    $('.GenericEmail').each(function() {
                        if ($(this).val() == "" && found == false) {
                            $(this).parent().parent().after(html);
                            $(this).parent().parent().remove();
                            found = true;
                        }
                    });
                    if (!found) {
                        $('#CreateTable > tbody > tr').eq(i).after(html);
                        i++;
                    }
                }
            });
        }
    };
    $(function() {
        $("#up_bulk").makeAsyncUploader({
            upload_url: "/Account/AsyncUpload", // Important! This isn't a directory, it's a HANDLER such as an ASP.NET MVC action method, or a PHP file, or a Classic ASP file, or an ASP.NET .ASHX handler. The handler should save the file to disk (or database).
            flash_url: '/Scripts/swfupload.swf',
            button_image_url: '/Resources/blankButton.png',
            upload_success_handler: success,
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    });
    var vars = {};
    var parts = unescape(window.location.href).replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
        vars[key] = value;
    });
    $('#Email').val(vars["email"]);
    if ($('#Email').val() !="") {$('#Email').focus(); $('#UserName').focus(); }
})

var validemail = false;
var validemails = false;
var validusername = false;



function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};




function validateGenericEmails() {
    var x = 0;
    $('.GenericEmail').each(function() {
        if (!isValidEmailAddress($(this).val())) {
            $(this).addClass("input-validation-error");
            $(this).parent().next().children(":first").text("The Email format is invalid.");
            x++;
        }
    });
    if (x == 0) {
        validemails = true;
    }
    validemails = false;
}

function validateEmail() {
    if ($('#IsNew').val() == "True") {
        $("#Email").removeClass("input-validation-error");
        $("#EmailMessage").text("");
        $('#spinnermsg').text("Checking Email...");
        $("#spinnermsg").show();
        $("#spinner").show();
        $.ajax({
            url: "/Account/EmailIsValid",
            data: ({ email: $('#Email').val() }),
            cache: false,
            success: function(response) {
                if (response == "user") {
                    $.ajax({
                        url: "/Account/GetUserDetails",
                        data: ({ email: $('#Email').val(), selectedrole: $('#SelectedRole').val() }),
                        cache: false,
                        success: function(html) {
                            $('#accountManagerContainer').html(html);
                            $("#Email").removeClass("input-validation-error");
                            $("#spinner").hide();
                            $('#spinnermsg').text("");
                            $("#spinnermsg").hide();
                            $('#EmailMessage').text("Email is already in use.");
                            validemail = true;
                        }
                    });
                }
                else if (response == "invalid") {
                    $("#Email").removeClass("input-validation-error");
                    $("#spinner").hide();
                    $('#spinnermsg').text("");
                    $("#spinnermsg").hide();
                    $('#EmailMessage').text("Email is invalid.");
                    validemail = false;
                }
                else {
                    if ($('#IsEditable').val() == "False") {
                        $.ajax({
                            url: "/Account/GetNewUserDetails",
                            data: ({ username: $('#UserName').val(), email: $('#Email').val(), firstname: $('#FirstName').val(),
                                lastname: $('#LastName').val(), organisation: $('#Organisation').val(), position: $('#Position').val(),
                                city: $('#City').val(), country: $('#Country').val(), selectedrole: $('#SelectedRole').val(), gender: $("input[@name=Gender]:checked").val(),
                                isgeneric: $("#IsGeneric").is(':checked')
                            }),
                            cache: false,
                            success: function(html) {
                                $('#accountManagerContainer').html(html);
                            }
                        });
                    }
                    if ($('#Email').val() == "") {
                        $("#Email").addClass("input-validation-error");
                        $("#spinner").hide();
                        $('#spinnermsg').text("");
                        $("#spinnermsg").hide();
                        $('#EmailMessage').text("The Email field is required.");
                        validemail = false;
                    }
                    else if (!isValidEmailAddress($('#Email').val())) {
                        $("#Email").addClass("input-validation-error");
                        $("#spinner").hide();
                        $('#spinnermsg').text("");
                        $("#spinnermsg").hide();
                        $('#EmailMessage').text("The Email format is invalid.");
                        validemail = false;
                    }
                    else {
                        $("#Email").removeClass("input-validation-error");
                        $("#spinner").hide();
                        $('#spinnermsg').text("");
                        $("#spinnermsg").hide();
                        $('#EmailMessage').text("The Email is valid.");
                        validemail = true;
                    }
                }
            }
        });
    }
}

function validateUserName() {
    if ($('#IsEditable').val() == "True") {
        $("#UserName").removeClass("input-validation-error");
        $("#UserNameMessage").text("");
        $("#spinner").show();
        $('#spinnermsg').text("Checking UserName...");
        $("#spinnermsg").show();
        if ($('#UserName').val() == "") {
            $("#UserName").addClass("input-validation-error");
            $('#spinnermsg').text("");
            $("#spinnermsg").hide();
            $("#spinner").hide();
            $('#UserNameMessage').text("The UserName field is required.");
            validusername = false;
        }
        else {
            $.ajax({
                url: "/Account/UserNameIsValid",
                data: ({ username: $('#UserName').val() }),
                cache: false,
                success: function(response) {
                    if (response == "False") {
                        $("#UserName").addClass("input-validation-error");
                        $('#spinnermsg').text("");
                        $("#spinnermsg").hide();
                        $("#spinner").hide();
                        $('#UserNameMessage').text("The UserName is already in use.");
                        validusername = false;
                    }
                    else {
                        $('#spinnermsg').text("");
                        $("#spinner").hide();
                        $("#spinnermsg").hide();
                        $('#UserNameMessage').text("The UserName is valid.");
                        validusername = true;
                    }
                }
            });
        }
    }
}

